package com.dahaiwuliang.code.controller;

import com.dahaiwuliang.code.pojo.Article;
import com.dahaiwuliang.code.pojo.Comment;
import com.dahaiwuliang.code.pojo.User;
import com.dahaiwuliang.code.server.ArticleService;
import com.dahaiwuliang.code.server.CommentService;
import com.dahaiwuliang.code.util.Consts;
import com.dahaiwuliang.code.util.HTMLUtil;
import com.dahaiwuliang.code.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**评论
 * @author bzd
 */
@Controller
@RequestMapping(value = "/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

     @Autowired
     private ArticleService articleService;

     @ResponseBody
     @PostMapping("/add")
public Map<String,Object> add(Comment comment, HttpSession session){
   Map<String,Object> map=new HashMap<>();
   comment.setCommentDate(new Date());
   comment.setContent(StringUtil.esc(comment.getContent()));
   comment.setState(0);
   comment.setUser((User) session.getAttribute(Consts.CURRENT_USER));
   commentService.save(comment);
    map.put("success",true);
    return  map;
}

/**
 * 分页查询某个资源评论信息
 */
  @ResponseBody
  @RequestMapping(value = "/list")
  public Map<String,Object> list(Comment comment, @RequestParam(value = "page",required = false)Integer page){
      comment.setState(1);
      Page<Comment> commentPage =commentService.List(comment,page,5, Sort.Direction.DESC,"commentDate");
      Map<String,Object> map=new HashMap<>();
      map.put("data",HTMLUtil.getCommentPageString(commentPage.getContent()));
      map.put("total",commentPage.getTotalPages());
      return  map;
  }
}
